<template>
	<div class="dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" :close-on-click-modal="false" width="1000px">
			<el-form ref="formRef" :model="state.ruleForm" :rules="state.rules">
				<el-row class="mb20" :gutter="20">
					<el-col :span="12">
						<el-form-item label="所属上级" prop="pid">
							<el-tree-select
								v-model="state.ruleForm.pid"
								:data="state.treeSelectData"
								:cache-data="state.cacheData"
								:props="state.pidProps"
								:load="pIdloadNode"
								lazy
								check-strictly
								clearable
								class="w100"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="菜单类型" prop="menu_type">
							<el-radio-group v-model="state.ruleForm.menu_type">
								<el-radio :value="1">菜单</el-radio>
								<el-radio :value="2">权限</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row class="mb20" :gutter="20">
					<el-col :span="12">
						<el-form-item label="菜单名称" prop="title">
							<el-input v-model="state.ruleForm.title" placeholder="请输入菜单名称" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="权限标识" prop="roles">
							<el-input v-model="state.ruleForm.roles" placeholder="请输入权限标识" clearable />
						</el-form-item>
					</el-col>
				</el-row>
				<template v-if="state.ruleForm.menu_type === 1">
					<el-row class="mb20" :gutter="20">
						<el-col :span="12">
							<el-form-item label="组件路径" prop="component">
								<el-input v-model="state.ruleForm.component" placeholder="请输入组件路径" clearable />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="组件重定向" prop="redirect">
								<el-input v-model="state.ruleForm.redirect" placeholder="请输入组件重定向" clearable />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row class="mb20" :gutter="20">
						<el-col :span="12">
							<el-form-item label="路由名称" prop="name">
								<el-input v-model="state.ruleForm.name" placeholder="请输入路由名称" clearable />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="路由路径" prop="path">
								<el-input v-model="state.ruleForm.path" placeholder="请输入路由路径" clearable />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row class="mb20" :gutter="20">
						<el-col :span="12">
							<el-form-item label="固定" prop="is_affix">
								<el-radio-group v-model="state.ruleForm.is_affix">
									<el-radio :value="1">是</el-radio>
									<el-radio :value="0">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="页面缓存" prop="is_keep_alive">
								<el-radio-group v-model="state.ruleForm.is_keep_alive">
									<el-radio :value="1">是</el-radio>
									<el-radio :value="0">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
					</el-row>
				</template>
				<el-row class="mb20" :gutter="20">
					<el-col v-if="state.ruleForm.menu_type === 1" :span="12">
						<el-form-item label="隐藏" prop="is_hide">
							<el-radio-group v-model="state.ruleForm.is_hide">
								<el-radio :value="1">是</el-radio>
								<el-radio :value="0">否</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="排序" prop="menu_sort">
							<el-input v-model="state.ruleForm.menu_sort" placeholder="请输入排序" clearable @input="onVerifiyNumberIntegerMenuSort" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<el-button @click="onCancel" size="default">取 消</el-button>
				<el-button type="primary" @click="onSubmit" :loading="state.dialog.submitLoading" size="default">提 交</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus';
import { nextTick, reactive, ref } from 'vue';
import { permissionApi } from '/@/api';
import { verifiyNumberInteger } from '/@/utils/toolsValidate';

let callback: Function = () => {};
let _node: any = null;
let _resolve: any = null;
const PermissionApi = permissionApi();
const state = reactive({
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitLoading: false,
	},
	ruleForm: {
		pid: '', // 上级菜单
		menu_type: 1, // 菜单类型（菜单/按钮）
		title: '', // 菜单名称
		roles: '', // 权限标识
		path: '', // 路由路径
		redirect: '', // 路由重定向，有子集 children 时
		component: '', // 组件路径
		menu_sort: '', // 菜单排序
		is_hide: 0, // 是否隐藏
		is_affix: 0, // 是否固定
		is_keep_alive: 1, // 是否缓存
		name: '', // 路由名称
		component_alias: '',
		// name: '', // 路由名称
		// is_link: false, // 是否外链
		// icon: '', // 菜单图标
		// link_url: '', // 外链/内嵌时链接地址（http:xxx.com），开启外链条件，
		// is_iframe: false, // 是否内嵌，开启条件，
	},
	rules: {
		title: [{ required: true, message: '菜单名称不能为空', trigger: ['blur'] }],
		roles: [{ required: true, message: '权限标识不能为空', trigger: ['blur'] }],
		component: [{ required: true, message: '组件路径不能为空', trigger: ['blur'] }],
		name: [{ required: true, message: '路由名称不能为空', trigger: ['blur'] }],
		path: [{ required: true, message: '路由路径不能为空', trigger: ['blur'] }],
	},
	pidProps: {
		value: 'id',
		label: 'title',
		children: 'children',
	},
	treeSelectData: [],
	cacheData: [] as any,
});
const formRef = ref();

/********** 触发事件 **********/
// 排序过滤
const onVerifiyNumberIntegerMenuSort = (val: string) => {
	state.ruleForm.menu_sort = verifiyNumberInteger(val);
};
// 取消
const onCancel = () => {
	state.dialog = {
		isShowDialog: false,
		type: '',
		title: '',
		submitLoading: false,
	};
};
// 提交
const onSubmit = () => {
	formRef.value.validate((valid: boolean) => {
		if (!valid) return;
		state.dialog.submitLoading = true;
		const info = state.ruleForm;
		const component_alias = {
			title: info.title,
			isLink: '',
			isHide: info.is_hide,
			isKeepAlive: info.is_keep_alive,
			isAffix: false,
			isIframe: false,
			roles: [info.roles],
			icon: state.ruleForm.pid === '' ? 'iconfont icon-caidan' : '',
		};
		if (state.dialog.type === 'add') {
			_permissionAdd({
				...state.ruleForm,
				icon: state.ruleForm.pid === '' ? 'iconfont icon-caidan' : '',
				component_alias: JSON.stringify(component_alias),
			});
		} else {
			_permissionEdit({
				...state.ruleForm,
				icon: state.ruleForm.pid === '' ? 'iconfont icon-caidan' : '',
				component_alias: JSON.stringify(component_alias),
			});
		}
	});
};

/********** 方法事件 **********/
// 打开
const openDialog = (data: any, row: any, fn: Function) => {
	state.dialog = {
		isShowDialog: true,
		type: data.type,
		title: data.title,
		submitLoading: false,
	};
	callback = fn;
	if (_node) {
		_node.childNodes = [];
		pIdloadNode(_node, _resolve);
	}
	nextTick(() => {
		formRef.value.resetFields();
		if (state.dialog.type !== 'add') {
			_permissionInfo({ permission_id: row.id }, 1);
			row.pid && _permissionInfo({ permission_id: row.pid }, 0);
		}
	});
};
// 请求节点
const pIdloadNode = (node: any, resolve: (arg0: any) => void) => {
	if (!node.level) {
		_node = node;
		_resolve = resolve;
	}
	_permissionList({ pid: node.level ? node.data.id : 0 }, node.level, resolve);
};

/********** 网络请求 **********/
// 权限菜单列表
const _permissionList = (params: Object, level: number, resolve: (arg0: any) => void) => {
	PermissionApi.permissionList(params).then((res: any) => {
		const list = res.data.list.filter((item: any) => item.menu_type === 1);
		let nodes = list.map((item: any) => ({
			...item,
			hasChildren: true,
		}));
		resolve(nodes);
	});
};
// 获取权限菜单信息
const _permissionInfo = (params: Object, level: number) => {
	PermissionApi.permissionInfo(params).then((res: any) => {
		if (level) {
			state.ruleForm = {
				...res.data.info,
				pid: res.data.info.pid ? res.data.info.pid : '',
				permission_id: res.data.info.id,
			};
		} else {
			state.cacheData = [res.data.info];
		}
	});
};
// 添加权限菜单
const _permissionAdd = (params: Object) => {
	PermissionApi.permissionAdd(params)
		.then(() => {
			ElMessage.success('操作成功！');
			onCancel();
			callback();
		})
		.catch(() => (state.dialog.submitLoading = false));
};
// 编辑权限菜单
const _permissionEdit = (params: Object) => {
	PermissionApi.permissionEdit(params)
		.then(() => {
			ElMessage.success('操作成功！');
			onCancel();
			callback();
		})
		.catch(() => (state.dialog.submitLoading = false));
};

/********** 方法向父组件暴露 **********/
defineExpose({ openDialog });
</script>
